package com.lqg.bookLibrary.adminController;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lqg.bookLibrary.common.constant.HostParam;
import com.lqg.bookLibrary.common.core.domain.JsonResult;
import com.lqg.bookLibrary.common.util.JwtUtils;
import com.lqg.bookLibrary.pojo.Users;
import com.lqg.bookLibrary.service.IUsersService;
import com.lqg.bookLibrary.service.webService.FileService;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/manage/user")
@PreAuthorize("hasAnyRole('a')")
public class ManageUserController {

    @Autowired
    private IUsersService usersService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private FileService fileService;


    @GetMapping("/read/{pageNum}")
    public JsonResult read(@PathVariable int pageNum) {
        long count = usersService.count();
        int maxCun = 20;
        int chu = (pageNum-1)*maxCun;
        List<Users> list = usersService.lambdaQuery()
                .last("limit " + chu + "," + maxCun)
                .list();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", list);
        jsonObject.put("pages", (int)(count/maxCun)+1);
        jsonObject.put("nowPage", pageNum);

        return JsonResult.success(jsonObject);
    }


    @PostMapping("/update")
    public JsonResult update(@RequestBody String post){
        Users users = JSON.parseObject(post, Users.class);
        Users one = usersService.lambdaQuery()
                .eq(Users::getUserId, users.getUserId()).one();
        if (!one.getPassword().equals(users.getPassword())) {
            users.setPassword(passwordEncoder.encode(users.getPassword()));
        }
        users.setUpdatedAt(null);
        users.setCreatedAt(null);
        usersService.updateById(users);
        Users one1 = usersService.lambdaQuery().eq(Users::getUsername, users.getUsername()).one();
        return JsonResult.success(one1);
    }


    @GetMapping("/delete/{id}")
    public JsonResult delete(@PathVariable Long id){
        boolean b = usersService.removeById(id);
        if (b) {
            return JsonResult.success();
        }else {
            return JsonResult.fail("删除失败");
        }
    }


    @PostMapping("/insert")
    public JsonResult insert(@RequestBody String post){
        Users users = JSON.parseObject(post, Users.class);
        users.setPassword(passwordEncoder.encode(users.getPassword()));

        boolean exists = usersService.lambdaQuery().eq(Users::getUsername, users.getUsername()).exists();

        if (exists) {
            return JsonResult.fail("用户名已存在");
        } else {
            users.setPassword(passwordEncoder.encode(users.getPassword()));
            usersService.save(users);
            Users one = usersService.lambdaQuery().eq(Users::getUsername, users.getUsername()).one();
            return JsonResult.success(one);
        }
    }

    @PostMapping("/avatar/upload")
    public JsonResult uploadAvatar(@RequestParam("avatar") MultipartFile zipFile,
                                   @RequestParam Long id){
        // 文件保存
        String filePath = HostParam.MAIN_PATH + "/user/avatar/";
        String fileName = id +"_avatar.jpg";
        String fwUri = HostParam.ACCESS_PATH + "/user/avatar/" +fileName;
        fileService.upLoadFile(zipFile, filePath, fileName);
        return JsonResult.success("success",fwUri);
    }

    @PostMapping("/search")
    public JsonResult search(@RequestBody String post){
        JSONObject jsonObject = JSONObject.parseObject(post);
        String condition = jsonObject.get("condition").toString();
        String content = jsonObject.get("content").toString();
        //System.out.printf(condition + "     " + content);

        condition = StrUtil.toUnderlineCase(condition);

        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq(condition, content);
        List<Users> list = usersService.list(wrapper);

        JSONObject result = new JSONObject();
        result.put("data", list);
        result.put("pages", 1);
        result.put("nowPage", 1);

        return JsonResult.success(result);
    }

}
